﻿$(function() {
	var loading = $("#my-modal-loading");
	var loadingtext = $("#loading_text");
	var headPath = localStorage.getItem("head_image");
	$(".img_test1").attr("src", headPath);
	var timestamp;
	var nonceStr;
	var signature;
	var url = location.href;
	var imageId1;
	var imageId2;
	var imageId3;

	var imageServerId1;
	var imageServerId2;
	var imageServerId3;

	var recordPath1;
	var recordPath2;
	var recordPath3;

	var recordServerPath1;
	var recordServerPath2;
	var recordServerPath3;

	var audioServerIds = "";
	
	var index = 1;

	var countdown = 60;
	var isPlay = 0;

	var is_encrypt = "1";
	var pwd = "";

	var is_pay = "1";
	var price;

	var type_id = "情感";
	var store_id = localStorage.getItem("query_id");
	loadingtext.text("初始化中...");
	loading.modal();
	$.ajax({
		type: "POST",
		url: "http://yx.fxtourong.com/V1/Wechat/getSignPackage",
		data: {
			token: localStorage.getItem("token"),
			url: url,
			verify: "yin@xiong8_(fx-tourong"
		},
		dataType: "json",
		success: function(data) {
			loading.modal('close');
			console.log(data);
			var code = data.code;
			if(code == "1") {
				timestamp = data.data.timestamp;
				nonceStr = data.data.nonceStr;
				signature = data.data.signature;
				wx.config({
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: 'wx7f13802caf31f385', // 必填，公众号的唯一标识
					timestamp: timestamp, // 必填，生成签名的时间戳
					nonceStr: nonceStr, // 必填，生成签名的随机串
					signature: signature, // 必填，签名，见附录1
					jsApiList: ['chooseImage', 'uploadImage', 'startRecord', 'stopRecord',
						'onVoiceRecordEnd', 'playVoice', 'pauseVoice',
						'stopVoice', 'onVoicePlayEnd', 'uploadVoice',
						'downloadVoice', 'downloadImage'
					] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				wx.ready(function() {
					console.log("aaaaaaaaaaaaaaaa");
					$("#openImage").click(function() {
						wx.chooseImage({
							count: 1, // 默认9
							sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
							success: function(res) {
//								onImageUp(res.localIds.toString(), 1);
								if(index == 1){
									onImageUp(res.localIds.toString(), 1);
									index++;
									imageId1 = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
									$("#image1").attr('src', imageId1);
									$("#openImage").css("display", "block");
									$("#image1").css("display", "inline");
								} else if (index == 2){
									onImageUp(res.localIds.toString(), 2);
									index++;
									imageId2 = res.localIds;
									$("#image2").attr('src', imageId2);
									$("#openImage").css("display", "block");
									$("#image2").css("display", "inline");
								} else if(index == 3) {
									onImageUp(res.localIds.toString(), 3);
									index++;
									imageId3 = res.localIds;
									$("#image3").attr('src', imageId3);
									$("#image3").css("display", "inline");
									$("#openImage").css("display", "none");
								}
							}
						});

					});
				});
			} else {
				alert("初始化失败:" + data.message);
			}
		},
		error:function(e){
			loading.modal('close');
			alert("初始化失败！");
		}
	});

	function onImageUp(path, index) {
		wx.uploadImage({
			localId: path, // 需要上传的图片的本地ID，由chooseImage接口获得
			isShowProgressTips: 0, // 默认为1，显示进度提示
			success: function(res) {
				if(index == 1) {
					imageServerId1 = res.serverId; // 返回图片的服务器端ID
				} else if(index == 2) {
					imageServerId2 = res.serverId; // 返回图片的服务器端ID
				} else {
					imageServerId3 = res.serverId; // 返回图片的服务器端ID
				}

			}
		});
	}

	$("select#sel_pwd").change(function() {
		var sel_yn = $(this).val();
		if(sel_yn == "是") {
			$("#create_pwd").css('visibility', 'visible');
			is_encrypt = "1";
		} else {
			$("#create_pwd").css('visibility', 'hidden');
			is_encrypt = "0";
		}
	});

	$("select#sel_pay").change(function() {
		var sel_yn = $(this).val();
		if(sel_yn == "是") {
			$("#pay_text").text("付费：");
			$("#pay_text_price").css("visibility", "visible");
			is_pay = "1";
		} else {
			$("#pay_text").text("免费");
			$("#pay_text_price").css("visibility", "hidden");
			is_pay = "0";
		}
	});

	$("select#sel_type").change(function() {
		type_id = $(this).val();
	});

	$("#post_create_topic").click(function() {
		var topname = $("#topic_name").val();
		var topdetail = $("#topic_detail").val();
		var imageServerIds = "";
		if(imageServerId1 !== null && imageServerId1 !== undefined && imageServerId1 !== '') {
			imageServerIds = imageServerId1;
			if(imageServerId2 !== null && imageServerId2 !== undefined && imageServerId2 !== '') {
				imageServerIds = imageServerId1 + "," + imageServerId2;
				if(imageServerId3 !== null && imageServerId3 !== undefined && imageServerId3 !== '') {
					imageServerIds = imageServerId1 + "," + imageServerId2 + "," + imageServerId3;
				}
			}
		}
		if(recordServerPath1 !== null && recordServerPath1 !== undefined && recordServerPath1 !== '') {
			audioServerIds = recordServerPath1;
			if(recordServerPath2 !== null && recordServerPath2 !== undefined && recordServerPath2 !== '') {
				audioServerIds = recordServerPath1 + "," + recordServerPath2;
				if(recordServerPath3 !== null && recordServerPath3 !== undefined && recordServerPath3 !== '') {
					audioServerIds = recordServerPath1 + "," + recordServerPath2 + "," + recordServerPath3;
				}
			}
		}
		if(imageServerIds == null || imageServerIds == undefined || imageServerIds == '') {
			new Toast({context:$('body'),message:'请至少上传一张图片'}).show();
			return;
		} else {
		}
		if(audioServerIds == null || audioServerIds == undefined || audioServerIds == '') {
			new Toast({context:$('body'),message:'您还未上传语音'}).show();
			return;
		} else {
		}
		if(is_encrypt == "0") {
			pwd = "";
		} else {
			pwd = $("#create_pwd").val();
		}
		if(is_pay == "0") {
			price = "";
		} else {
			price = $("#create_price").val();
		}

		$("#data_json").text("1");
		$("#audio").text("3:" + recordServerPath1);
		$("#picture").text("参数:" + topname + ":" + imageServerIds + ":" + topdetail + ":" + audioServerIds + ":" + is_encrypt + ":" + pwd + ":" + is_pay + ":" +
			price + ":" + type_id + ":" + timeStr);
		var urlPath = "http://yx.fxtourong.com/V1/Goods/createTopic" + "?store_id=" + store_id;

		$.ajax({
			type: "POST",
			url: urlPath,
			data: {
				token: localStorage.getItem("token"),
				name: topname,
				cover: imageServerIds,
				details: topdetail,
				audio: audioServerIds,
				is_encrypt: is_encrypt,
				pwd: pwd,
				is_pay: is_pay,
				price: price,
				type_id: type_id
			},
			dataType: "json",
			success: function(data) {
				$("#data_json").text("2");
				console.log(data);
				var code = data.code;
				console.log(code);
				$("#data_json").text("是否创建成功:" + code + ":" + data.message);
				if(code == "1") {
					console.log("创建话题成功");
				}
			}
		});
	});

	function settime() {
		if(countdown == 0) {
			countdown = 60;
			$("#timecount").text(60);
			return;
		} else {
			$("#timecount").text(countdown);
			countdown--;
		}
		setTimeout(function() {
			settime()
		}, 1000)
	}
	
	$("#upload").click(function() {
		var urlPath = "http://yx.fxtourong.com/V1/Audio/uploadAudio" + "?store_id=" + store_id;
		var formData = new FormData();
		formData.append("myfile", document.getElementById("file1").files[0]);
		console.log("token:" + localStorage.getItem("token"));
		$.ajax({
			url: urlPath,
			type: "POST",
			data: formData,
			/**
                    *必须false才会自动加上正确的Content-Type
                    */
                    contentType: false,
                    /**
                    * 必须false才会避开jQuery对 formdata 的默认处理
                    * XMLHttpRequest会对 formdata 进行正确的处理
                    */
                    processData: false,
			success: function(data) {
				var code = data.code;
				if(code == 1){
					audioServerIds = data.data;
				} else {
					alert("上传失败：" + data.message);
				}
				
			},
			error: function() {
				alert("上传失败！");
			}
		});
	});

});

function removejscssfile(filename, filetype) {
	var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none"
	var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none"
	var allsuspects = document.getElementsByTagName(targetelement)
	for(var i = allsuspects.length; i >= 0; i--) {
		if(allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
			allsuspects[i].parentNode.removeChild(allsuspects[i])
	}
}